// 引用axios
import axios from 'axios'
const pageConfig = require('./config');
var qs = require('qs');
// 自定义判断元素类型JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/*
  接口处理函数
  这个函数每个项目都是不一样的，我现在调整的是适用于
  https://cnodejs.org/api/v1 的接口，如果是其他接口
  需要根据接口的参数进行调整。参考说明文档地址：
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是，不同的接口的成功标识和失败提示是不一致的。
  另外，不同的项目的处理方法也是不一致的，这里出错就是简单的alert
*/
const clearRequest = {
  source: {
    token: null,
    cancel: null
  }
}
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 配置发送请求拦截器
axios.interceptors.request.use(config => {
  config.cancelToken = clearRequest.source.token;// 这句很重要
  return config
}, error => {
  return Promise.reject(error)
})
function apiAxios1(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'json',
    baseURL: pageConfig.root1,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res.data)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}
function apiAxios2(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'json',
    baseURL: pageConfig.root2,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res.data)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}
function getExel1(method, url, params, success, failure) {
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'arraybuffer',
    baseURL: pageConfig.root1,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res.data)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}
function getExel2(method, url, params, success, failure) {
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'arraybuffer',
    baseURL: pageConfig.root2,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res.data)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}
function getGeo1(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'json',
    baseURL: pageConfig.root1,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}
function getGeo2(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? qs.stringify(params) : null,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: 'json',
    baseURL: pageConfig.root2,
    cancelToken: source.token,
  })
    // axios.post(url,params)
    .then(function (res) {
      // if (res.data.status.toUpperCase() === 'OK') {
      //   if (success) {
      success(res)
      // }
      // } else {
      //   if (failure) {
      //     failure(res.data)
      //   } else {
      //     console.log('error: ' +url+'--'+ JSON.stringify(res.data))
      //   }
      // }
    })
    .catch(function (err) {
      let res = err.response
      if (err) {
        if (failure) {
          if (window.navigator.onLine == true) {
            let res = { msg: '系统繁忙，请稍后重试' };
            failure(res)
          } else {
            let res = { msg: '网络异常' };
            failure(res)
          }
        }
        console.log('api error, HTTP CODE: ' + url)
        console.log(err)
        // alert('网络繁忙，请稍后重试')
      }
    })
}

var apiAjax = {
  get1: function (url, params, success, failure) {
    return apiAxios1('GET', url, params, success, failure)
  },
  getgeojson1: function (url, params, success, failure) {
    return getGeo1('POST', url, params, success, failure)
  },
  post1: function (url, params, success, failure) {
    return apiAxios1('POST', url, params, success, failure, )
  },
  put1: function (url, params, success, failure) {
    return apiAxios1('PUT', url, params, success, failure)
  },
  delete1: function (url, params, success, failure) {
    return apiAxios1('DELETE', url, params, success, failure)
  },
  fileGet1: function (url, params, success, failure) {
    return getExel1('POST',url, params, success, failure)
  },
  get2: function (url, params, success, failure) {
    return apiAxios2('GET', url, params, success, failure)
  },
  getgeojson2: function (url, params, success, failure) {
    return getGeo2('POST', url, params, success, failure)
  },
  post2: function (url, params, success, failure) {
    return apiAxios2('POST', url, params, success, failure, )
  },
  put2: function (url, params, success, failure) {
    return apiAxios2('PUT', url, params, success, failure)
  },
  delete2: function (url, params, success, failure) {
    return apiAxios2('DELETE', url, params, success, failure)
  },
  fileGet2: function (url, params, success, failure) {
    return getExel2('POST',url, params, success, failure)
  }
}
// 返回在vue模板中的调用接口
export default {
  install(Vue) {
    Vue.prototype.$http = apiAjax
    Vue.http = apiAjax
  },
  $http: apiAjax,
  clearRequest,
  apiAxios1,
  apiAxios2
}

export const $http = apiAjax
